import type { Router } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'

const whiteList = ['/login', '/404', '/403']
const authEnabled = import.meta.env.VITE_AUTH_ENABLED === 'true'

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, _from, next) => {
    // 如果未开启权限控制，直接通过
    if (!authEnabled) {
      next()
      return
    }

    const userStore = useUserStore()
    const permissionStore = usePermissionStore()

    // 白名单直接通过
    if (whiteList.includes(to.path)) {
      next()
      return
    }

    // 检查是否已登录
    if (!userStore.token) {
      next(`/login?redirect=${to.path}`)
      return
    }

    // 获取用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        window['$message'].error('获取用户信息失败')
        next('/login')
        return
      }
    }

    // 生成动态路由
    if (!permissionStore.isInitialized) {
      try {
        await permissionStore.buildRoutes(userStore.userInfo?.roles || [])
        next({ ...to, replace: true })
      } catch (error) {
        window['$message'].error('生成路由失败')
        next('/403')
      }
      return
    }

    // 检查页面权限
    if (to.meta?.permissions) {
      const hasPermission = permissionStore.hasPermission(to.meta.permissions as string[])
      if (!hasPermission) {
        window['$message'].error('无访问权限')
        next('/403')
        return
      }
    }

    next()
  })
}
